// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

import {
  post
} from '../../utils/http'

Page({
  data: {
    motto: '登录',
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
    loading: false
  },
  onLogin(e) {
    // 登录
    if (!this.data.userInfo.nickName) {
      wx.showToast({
        title: '昵称不能为空',
        icon: 'none'
      })
      return
    }

    if (!this.data.userInfo.avatarUrl) {
      wx.showToast({
        title: '头像不能为空',
        icon: 'none'
      })
      return
    }

    if (this.data.loading) {
      return
    }



    this.setData({
      loading: true
    })

    const {
      nickName,
      avatarUrl
    } = this.data.userInfo

    let that = this

    wx.login({
      success: res => {
        console.log(res)
        post("/user/auth/login", {
          code: `${res.code}`,
          nickName: nickName,
          avatarUrl: avatarUrl
        }).then(res => {
          const {
            openId,
            token
          } = res.data
          if (token) {
            wx.setStorageSync('token', token)
            getApp().globalData.userInfo = this.data.userInfo
            wx.switchTab({
              url: '/pages/index/index',
              success: function (params) {
                that.setData({
                  loading: false
                })
              }
            })
            return
          }
        }).catch(err => {
          wx.showToast({
            title: '登录失败,请检查网络: ' + err,
            icon: 'none'
          })
          that.setData({
            loading: false
          })
        })
      }
    })
  },
  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    const {
      nickName
    } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  onInputChange(e) {
    const nickName = e.detail.value
    const {
      avatarUrl
    } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
  },
  getUserProfile(e) {
    wx.getUserProfile({
      desc: '展示用户信息',
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },
})